package com.test.mvcframework.servlet;

import com.test.mvcframework.ioc.ApplicationContext;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author felix
 */
public abstract class FrameworkServlet extends HttpServlet {
    private Properties properties;

    protected ApplicationContext context;

    /**
     * 加载配置文件
     */
    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream =
                this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties = new Properties();
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        // 1 加载配置文件 springmvc.properties
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);

        try {
            // 初始化容器
            this.initApplicationContext();

            //初始化servlet
            this.initServletBeans();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化容器
     * @throws Exception
     */
    private void initApplicationContext() throws Exception {
        context = new ApplicationContext();
        context.init(properties.getProperty("basePackage"));
    }

    private void initServletBeans() {
        initStrategies();
    }

    protected abstract void initStrategies();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        processRequest(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        processRequest(req, resp);
    }

    /**
     * 处理请求
     * @param request
     * @param response
     */
    private void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        doService(request, response);
    }

    /**
     * 执行逻辑， 交由子类实现
     * @param request
     * @param response
     */
    protected abstract void doService(HttpServletRequest request, HttpServletResponse response)
            throws IOException;
}
